package com.jemaa.news.web;


import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.jemaa.news.app.NotificationService;

@SuppressWarnings("unchecked")
public class NotifyingExceptionResolver extends  SimpleMappingExceptionResolver {
	  private Properties priorityExpMappings;
	  
	  private Map priorityNSMappings;
	  private String notificationMessage = null;

	  protected final Log logger = LogFactory.getLog(getClass());

	  public void setPriorityExceptionMappings(Properties  priorityExpMappings){
	    this.priorityExpMappings = priorityExpMappings;
	  }

	  public void setPriorityNotificationServicesMappings (Map priorityNSMappings){
	    this.priorityNSMappings = priorityNSMappings;
	  }

	  public void setNotificationMessage(String message){
	    this.notificationMessage = message;
	  }

	  @Override
	  protected ModelAndView doResolveException(HttpServletRequest request,  HttpServletResponse response, Object handler, Exception ex) {
		  logger.warn("An Exception has occured in the application", ex);
	    sendNotification(ex);
	    return super.doResolveException(request, response, handler, ex);
	  }

	  private void sendNotification(Exception ex) {
	    String priority = resolvePriority(this.priorityExpMappings, ex);
	    NotificationService notificationService = resolveNotificationService (this.priorityNSMappings, priority);
	    String message = (notificationMessage == null ? priority :  notificationMessage);

	    if(notificationService != null) {
	    	logger.debug("notification message was sent");
	    	notificationService.sendNotification(message, ex);
	    }
	  }

	  private String resolvePriority(Properties priorityExpMappings,  Exception ex){
	    return this.findMatchingViewName(priorityExpMappings, ex);
	  }

	  private NotificationService resolveNotificationService (Map priorityNSMappings, String priority){
	    NotificationService notificationService = null;
	    notificationService = (NotificationService) priorityNSMappings.get(priority);
	    if (notificationService != null && logger.isDebugEnabled()) {
	      logger.debug("Resolving to a notification service for priority ["  + priority + "]");
	    }
	    return notificationService;
	  }
	}